﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BestPrice.Core
{
    using Common;

    public abstract class Manager<E, Key> : IManager<E, Key>
        where E : BaseEntity
        where Key : BaseKey
    {
        private static String _EntityName;
        public static String EntityName
        {
            get
            {
                if (String.IsNullOrEmpty(_EntityName))
                    _EntityName = typeof(E).Name;
                return _EntityName;
            }
        }

        private BestPriceDataContext _Ctx;
        public BestPriceDataContext Ctx
        {
            get
            {
                if (_Ctx == null)
                    _Ctx = BestPriceDataContext.GetDbContext();
                return _Ctx;
            }
        }

        public E GetByID(Key key)
        {
            return Ctx.GetByID<E, Key>(key);
        }

        public virtual void BeforeInsert(E obj)
        {
        }

        public virtual void Insert(E obj)
        {
            try
            {
                BeforeInsert(obj);
                Ctx.Insert(obj);
                AfterInsert(obj);
            }
            catch { }
        }

        public virtual void AfterInsert(E obj)
        {
        }

        public virtual void BeforeUpdate(E obj)
        {
        }

        public virtual void Update(E obj)
        {
            try
            {
                BeforeUpdate(obj);
                Ctx.Update(obj);
                AfterUpdate(obj);
            }
            catch { }
        }

        public virtual void AfterUpdate(E obj)
        {
        }

        public virtual void BeforeDelete(E obj)
        {
        }

        public virtual void Delete(E obj)
        {
            try
            {
                BeforeDelete(obj);
                Ctx.Delete(obj);
                AfterDelete(obj);
            }
            catch { }
        }

        public virtual void AfterDelete(E obj)
        {
        }

        public virtual void Delete(Key key)
        {
            try
            {
                var obj = GetByID(key);
                BeforeDelete(obj);
                Ctx.Delete(obj);
                AfterDelete(obj);
            }
            catch { }
        }

        public virtual bool Exist(Key key)
        {
            var obj = GetByID(key);
            return obj != null;
        }
    }
}
